/**
 * ModGames (C) 2007 Pedro Miller Rabinovitch.
 * 
 * Permission is hereby granted to copy and use this material for any free or educational purpose.
 * Please do not use this for commercial purposes before letting me know (but it'll be fine).
 * 
 * Contact me via gmail, account pedromr
 * http://exodia.org
 * 
 * $Id: SnakePiece.java 42 2007-12-09 16:10:47Z pedromr $
 */
import javax.microedition.lcdui.Image;

import exodia.Actor;
import exodia.ActorDefinition;

public class SnakePiece extends Actor {
	public int col, row;

	public SnakePiece ahead;

	public int orientation;

	static final int O_RIGHT = 0;

	static final int O_DOWN = 1;

	static final int O_LEFT = 2;

	static final int O_UP = 3;

	public int arrFrames[];
	public Image arrImages[];

	public SnakePiece(SnakePiece ahead, ActorDefinition actorDefinition) {
		super(actorDefinition);

		// defineReferencePixel(frameWidth/2, frameHeight/2);
		this.ahead = ahead;
		this.orientation = O_RIGHT;		
	}

	/**
	 * Set a specific image strip for an orientation
	 * 
	 * @param orient
	 *            Image's orientation (O_DOWN, O_LEFT, O_RIGHT, O_UP);
	 * @param image
	 *            The image strip
	 * @param nFrames
	 *            Number of animation frames in the strip
	 */
	public void setOrientationImage(int orient, Image image, int nFrames) {
		if (arrFrames == null) {
			arrFrames = new int[4];
			arrImages = new Image[4];
		}
		arrFrames[orient] = nFrames;
		arrImages[orient] = image;
	}

	public void tick(int deltaMS) {
		; // TODO animation here instead of per advance?
	}

	public void stepForward() {
		nextFrame();
		if (ahead != null) {
			// follow the one ahead of me
			col = ahead.col;
			row = ahead.row;
			setOrientation(ahead.orientation);
		} else {
			// head
			switch (orientation) {
			case SnakePiece.O_DOWN:
				row++;
				break;
			case SnakePiece.O_UP:
				row--;
				break;
			case SnakePiece.O_RIGHT:
				col++;
				break;
			case SnakePiece.O_LEFT:
				col--;
				break;
			}
		}
	}

	public void setOrientation(int orient) {
		if (orient < 0 || orient > 3)
			throw new IllegalArgumentException("Invalid orientation: " + orient);
		if (orient != this.orientation) {
			setAnimation(orient);			
			this.orientation = orient;
			setTransform(transform);
		}
	}
}
